/*
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-10-08 13:53:56
 * @LastEditTime : 2023-12-29 13:48:26
 */
import { Provide, Inject, Get, Post, Body, ALL } from '@midwayjs/decorator';
import { CoolController, BaseController } from '@cool-midway/core';
import { BaseSysUserEntity } from '../../entity/sys/user';
import { BaseSysLoginService } from '../../service/sys/login';
import { BaseSysPermsService } from '../../service/sys/perms';
import { BaseSysUserService } from '../../service/sys/user';
import { Context } from '@midwayjs/koa';
import { CoolFile } from '@cool-midway/file';
import { buildUUID } from '../../../../comm/uuid';
const core_1 = require('@cool-midway/core');
const moment = require('moment');
const path = require('path');
const fs = require('fs');
const _ = require('lodash');

/**
 * Base 通用接口 一般写不需要权限过滤的接口
 */
@Provide()
@CoolController()
export class BaseCommController extends BaseController {
  @Inject()
  baseSysUserService: BaseSysUserService;

  @Inject()
  baseSysPermsService: BaseSysPermsService;

  @Inject()
  baseSysLoginService: BaseSysLoginService;

  @Inject()
  ctx: Context;

  @Inject()
  coolFile: CoolFile;

  /**
   * 获得个人信息
   */
  @Get('/person', { summary: '个人信息' })
  async person() {
    return this.ok(await this.baseSysUserService.person());
  }

  /**
   * 修改个人信息
   */
  @Post('/personUpdate', { summary: '修改个人信息' })
  async personUpdate(@Body(ALL) user: BaseSysUserEntity) {
    await this.baseSysUserService.personUpdate(user);
    return this.ok();
  }

  /**
   * 权限菜单
   */
  @Get('/permmenu', { summary: '权限与菜单' })
  async permmenu() {
    return this.ok(
      await this.baseSysPermsService.permmenu(this.ctx.admin.roleIds)
    );
  }

  /**
   * 文件上传
   */
  @Post('/upload', { summary: '文件上传' })
  async upload() {
    // return this.ok(await this.coolFile.upload(this.ctx));
    const { fields, files } = this.ctx;
    const getPath = async () => {
      try {
        const { dir, key } = fields;
        if (_.isEmpty(files)) {
          throw new core_1.CoolCommException('上传文件为空');
        }
        const file = files[0];
        const extension = file.filename.split('.').pop();
        const uuname = key;
        const name =
          (dir || moment().format('YYYYMMDD')) +
          '/' +
          (uuname || `${buildUUID()}.${extension}`);
        const target = path.join(
          this.baseApp.getBaseDir(),
          '..',
          `public/uploads/${name}`
        );
        const dirPath = path.join(
          this.baseApp.getBaseDir(),
          '..',
          `public/uploads/${dir || moment().format('YYYYMMDD')}`
        );
        if (!fs.existsSync(dirPath)) {
          fs.mkdirSync(dirPath, { recursive: true });
        }
        const data = await fs.readFileSync(file.data);
        await fs.writeFileSync(target, data);
        return {
          path: `/public/uploads/${name}`,
          fullPath: `${
            this.baseApp.getConfig().cool.file.domain
          }/public/uploads/${name}`,
        };
      } catch (err) {
        // this.coreLogger.error(err) as any;
        throw new core_1.CoolCommException('上传失败');
      }
    };
    const { path: fpath } = await getPath();
    return this.ok(fpath);
  }

  /**
   * 文件上传模式，本地或者云存储
   */
  @Get('/uploadMode', { summary: '文件上传模式' })
  async uploadMode() {
    return this.ok(await this.coolFile.getMode());
  }

  /**
   * 退出
   */
  @Post('/logout', { summary: '退出' })
  async logout() {
    await this.baseSysLoginService.logout();
    return this.ok();
  }
}
